<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="函数式编程 高级函数 JavaScript,">





  <link rel="alternate" href="/atom.xml" title="YauCheun's Blog" type="application/atom+xml">






<meta name="description" content="昨天进行了人人网的面试，其中在二面中面试官问了“什么是函数式编程”这个问题，我只是听说过这个东西，但是让我讲就讲不出来，最后结束的时候给我的评价就是  js基础还行, 但是深入理解不够, 还有一个最关键的就是知识点看到了最好搞懂搞透彻, 不可以自己推测, 但是可以自己做demo实验自己的推测  经过这次面试后也发现和认识了自己的不足的地方，在这里也总结记录一下自己学习的JS的函数式编程">
<meta name="keywords" content="函数式编程 高级函数 JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript 函数式编程">
<meta property="og:url" content="http://yoursite.com/2019/08/30/函数式编程/index.html">
<meta property="og:site_name" content="YauCheun&#39;s Blog">
<meta property="og:description" content="昨天进行了人人网的面试，其中在二面中面试官问了“什么是函数式编程”这个问题，我只是听说过这个东西，但是让我讲就讲不出来，最后结束的时候给我的评价就是  js基础还行, 但是深入理解不够, 还有一个最关键的就是知识点看到了最好搞懂搞透彻, 不可以自己推测, 但是可以自己做demo实验自己的推测  经过这次面试后也发现和认识了自己的不足的地方，在这里也总结记录一下自己学习的JS的函数式编程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190829211452652.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lhdUNoZXVu,size_16,color_FFFFFF,t_70">
<meta property="og:updated_time" content="2019-08-30T14:28:07.601Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript 函数式编程">
<meta name="twitter:description" content="昨天进行了人人网的面试，其中在二面中面试官问了“什么是函数式编程”这个问题，我只是听说过这个东西，但是让我讲就讲不出来，最后结束的时候给我的评价就是  js基础还行, 但是深入理解不够, 还有一个最关键的就是知识点看到了最好搞懂搞透彻, 不可以自己推测, 但是可以自己做demo实验自己的推测  经过这次面试后也发现和认识了自己的不足的地方，在这里也总结记录一下自己学习的JS的函数式编程">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20190829211452652.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lhdUNoZXVu,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<style>
    .pace .pace-progress {
        background: #1E92FB; /*进度条颜色*/
        height: 3px;
    }
    .pace .pace-progress-inner {
         box-shadow: 0 0 10px #1E92FB, 0 0 5px     #1E92FB; /*阴影颜色*/
    }
    .pace .pace-activity {
        border-top-color: #1E92FB;    /*上边框颜色*/
        border-left-color: #1E92FB;    /*左边框颜色*/
    }
</style>



  <link rel="canonical" href="http://yoursite.com/2019/08/30/函数式编程/">





  <title>JavaScript 函数式编程 | YauCheun's Blog</title>
  








 
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
  

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">YauCheun's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Thoughts, stories and ideas</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/08/30/函数式编程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="YauCheun">
      <meta itemprop="description" content>
      <meta itemprop="image" content="http://tva2.sinaimg.cn/crop.0.0.768.768.1024/6cc1c2cfjw8eh3kv8yvs9j20lc0lcdgl.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="YauCheun's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaScript 函数式编程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-30T11:54:01+08:00">
                2019-08-30
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          



          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>昨天进行了人人网的面试，其中在二面中面试官问了“什么是函数式编程”这个问题，我只是听说过这个东西，但是让我讲就讲不出来，最后结束的时候给我的评价就是</p>
<blockquote>
<p>js基础还行, 但是深入理解不够, 还有一个最关键的就是知识点看到了最好搞懂搞透彻, 不可以自己推测, 但是可以自己做demo实验自己的推测</p>
</blockquote>
<p>经过这次面试后也发现和认识了自己的不足的地方，在这里也总结记录一下自己学习的JS的函数式编程</p>
<a id="more"></a>

<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><h3 id="一、什么是函数式编程？"><a href="#一、什么是函数式编程？" class="headerlink" title="一、什么是函数式编程？"></a>一、什么是函数式编程？</h3><blockquote>
<p>我的理解是函数式编程就是一种抽象程度很高的编程范式，纯粹的函数式编程语言编写的函数可以看成没有变量，因此，任意一个函数，只要输入是确定的，输出就是确定的。.函数式编程不是用函数来编程，也不是传统的面向过程编程。主旨在于将复杂的函数符合成简单的函数（计算理论，或者递归论，或者拉姆达演算）。运算过程尽量写成一系列嵌套的函数调用。函数式编程我觉得更贴近于数学思想或者说计算。</p>
</blockquote>
<h3 id="二、函数式编程的特性"><a href="#二、函数式编程的特性" class="headerlink" title="二、函数式编程的特性"></a>二、函数式编程的特性</h3><h6 id="1-函数是”第一等公民”"><a href="#1-函数是”第一等公民”" class="headerlink" title="1.函数是”第一等公民”"></a>1.函数是”第一等公民”</h6><p>所谓”第一等公民”（first class），指的是函数与其他数据类型一样，处于平等地位，可以赋值给其他变量，也可以作为参数，传入另一个函数，或者作为别的函数的返回值。<br>举例来说，下面代码中的print变量就是一个函数，可以作为另一个函数的参数。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="keyword">print</span> = <span class="function"><span class="keyword">function</span><span class="params">(i)</span></span>&#123; console.log(i);&#125;;</span><br><span class="line">　　[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>].<span class="keyword">forEach</span>(<span class="keyword">print</span>);</span><br></pre></td></tr></table></figure>

<h6 id="2-只用”表达式”，不用”语句”"><a href="#2-只用”表达式”，不用”语句”" class="headerlink" title="2.只用”表达式”，不用”语句”"></a>2.只用”表达式”，不用”语句”</h6><p>“表达式”（expression）是一个单纯的运算过程，总是有返回值；”语句”（statement）是执行某种操作，没有返回值。函数式编程要求，只使用表达式，不使用语句。也就是说，每一步都是单纯的运算，而且都有返回值。<br>原因是函数式编程的开发动机，一开始就是为了处理运算（computation），不考虑系统的读写（I/O）。”语句”属于对系统的读写操作，所以就被排斥在外。<br>当然，实际应用中，不做I/O是不可能的。因此，编程过程中，函数式编程只要求把I/O限制到最小，不要有不必要的读写行为，保持计算过程的单纯性。</p>
<h6 id="3-没有”副作用”"><a href="#3-没有”副作用”" class="headerlink" title="3.没有”副作用”"></a>3.没有”副作用”</h6><p>所谓”副作用”（side effect），指的是函数内部与外部互动（最典型的情况，就是修改全局变量的值），产生运算以外的其他结果。<br>函数式编程强调没有”副作用”，意味着函数要保持独立，所有功能就是返回一个新的值，没有其他行为，尤其是不得修改外部变量的值。</p>
<h6 id="4-不修改状态"><a href="#4-不修改状态" class="headerlink" title="4.不修改状态"></a>4.不修改状态</h6><p>在函数式编程中，我们通常理解的变量在函数式编程中也被函数代替了：在函数式编程中变量仅仅代表某个表达式。这里所说的’变量’是不能被修改的。所有的变量只能被赋一次初值。（下面会详细介绍变量被函数代替）</p>
<h6 id="5-引用透明性"><a href="#5-引用透明性" class="headerlink" title="5.引用透明性"></a>5.引用透明性</h6><p>函数程序通常还加强引用透明性，即如果提供同样的输入，那么函数总是返回同样的结果。就是说，表达式的值不依赖于可以改变值的全局状态。</p>
<h2 id="三、函数式编程常用核心概念和技术"><a href="#三、函数式编程常用核心概念和技术" class="headerlink" title="三、函数式编程常用核心概念和技术"></a>三、函数式编程常用核心概念和技术</h2><h6 id="1-纯函数"><a href="#1-纯函数" class="headerlink" title="1.纯函数"></a>1.纯函数</h6><p>什么是纯函数呢？</p>
<p>对于相同的输入，永远会得到相同的输出，而且没有任何可观察的副作用，也不依赖外部环境的状态的函数，叫做纯函数。<br>举个栗子：</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var xs = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];<span class="comment">// Array.slice是纯函数，因为它没有副作用，对于固定的输入，输出总是固定的</span></span><br><span class="line">xs.slice(<span class="number">0</span>,<span class="number">3</span>);</span><br><span class="line">xs.slice(<span class="number">0</span>,<span class="number">3</span>);</span><br><span class="line">xs.splice(<span class="number">0</span>,<span class="number">3</span>);<span class="comment">// Array.splice会对原array造成影响，所以不纯</span></span><br><span class="line">xs.splice(<span class="number">0</span>,<span class="number">3</span>);</span><br></pre></td></tr></table></figure>

<h6 id="2-函数柯里化（高级函数）"><a href="#2-函数柯里化（高级函数）" class="headerlink" title="2.函数柯里化（高级函数）"></a>2.函数柯里化（高级函数）</h6><p>高阶函数，就是把函数当参数，把传入的函数做一个封装，然后返回这个封装函数,达到更高程度的抽象。<br>我的理解：传递给函数一部分参数来调用它，让它返回一个函数去处理剩下的参数。</p>
<p>看一个例子：</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 柯里化之前</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span><span class="params">(x, y)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line">add(<span class="number">1</span>, <span class="number">2</span>) <span class="comment">// 3</span></span><br><span class="line"><span class="comment">// 柯里化之后</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addX</span><span class="params">(y)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">(x)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x + y;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line">addX(<span class="number">2</span>)(<span class="number">1</span>) <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>柯里化可以理解为是一种“预加载”函数的方法，通过传递较少的参数，得到一个已经记住了这些参数的新函数，某种意义上讲，这是一种对参数的“缓存”，是一种非常高效的编写函数的方法。</p>
</blockquote>
<h6 id="3-函数组合"><a href="#3-函数组合" class="headerlink" title="3.函数组合"></a>3.函数组合</h6><p>为了解决函数嵌套过深，洋葱代码：h(g(f(x)))，我们需要用到“函数组合”，我们可以<br>来用柯里化来改他，让多个函数像拼积木一样。</p>
<p>函数编程的函数组合：两个纯函数组合之后返回了一个新函数,举个例子：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compose = <span class="function"><span class="keyword">function</span>(<span class="params">f,g</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> f(g(x));</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> toUpperCase = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line"><span class="keyword">return</span> x.toUpperCase();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> exclaim = <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line"><span class="keyword">return</span> x + <span class="string">"!"</span>;</span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">const</span> shout = compose( exclaim , toUpperCase );</span><br><span class="line"> </span><br><span class="line"><span class="built_in">console</span>.log(shout(<span class="string">"hello world"</span>)); <span class="comment">//HELLO WORLD!</span></span><br></pre></td></tr></table></figure>

<p>可以对他简化一下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> compose=<span class="function">(<span class="params">f,g</span>)=&gt;</span>(<span class="function"><span class="params">x</span>=&gt;</span>f(g(x)))</span><br><span class="line"><span class="keyword">const</span> toUpperCase=<span class="function"><span class="params">x</span>=&gt;</span>x.toUpperCase()</span><br><span class="line"><span class="keyword">const</span> exclaim=<span class="function"><span class="params">x</span>=&gt;</span>x+<span class="string">'!'</span></span><br><span class="line"><span class="keyword">const</span> shout=compose(exclaim,toUpperCase)</span><br><span class="line"><span class="built_in">console</span>.log(shout(<span class="string">'hello world'</span>));  <span class="comment">//HELLO WORLD!</span></span><br></pre></td></tr></table></figure>

<p><strong>compose</strong>中的参数的顺序是随意的，这就类似于乘法中的交换律 <strong>x<em>y=y</em>x</strong>,<br>所以函数式编程贴近于数学计算。<br><img src="https://img-blog.csdnimg.cn/20190829211452652.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lhdUNoZXVu,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h6 id="4-递归与尾递归"><a href="#4-递归与尾递归" class="headerlink" title="4.递归与尾递归"></a>4.递归与尾递归</h6><p>指函数内部的最后一个动作是函数调用。 该调用的返回值， 直接返回给函数。 函数调用自身， 称为递归。 如果尾调用自身， 就称为尾递归。 递归需要保存大量的调用记录， 很容易发生栈溢出错误， 如果使用尾递归优化， 将递归变为循环， 那么只需要保存一个调用记录， 这样就不会发生栈溢出错误了。通俗点说，尾递归最后一步需要调用自身，并且之后不能有其他额外操作。<br>举个例子：我的理解为满足递归条件相当于捕鱼时先撒网，等达到递归边界即捕到鱼时，再返回自身及收网；尾递归就为当捕到鱼时鱼已经到你手里了，具体举个例子：</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 不是尾递归，无法优化</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">factorial</span><span class="params">(n)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (n === <span class="number">1</span>) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> n * factorial(n - <span class="number">1</span>);</span><br><span class="line">&#125;   <span class="comment">//这里的递归当到达边界条件时会把值返回给上一个调用它的函数</span></span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">factorial</span><span class="params">(n, total)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (n === <span class="number">1</span>) <span class="keyword">return</span> total;</span><br><span class="line">    <span class="keyword">return</span> factorial(n - <span class="number">1</span>, n * total);</span><br><span class="line">&#125; <span class="comment">//ES6强制使用尾递归</span></span><br><span class="line"><span class="comment">// 这里的尾递归就是当到底边界条件时直接将结果 return 出来</span></span><br></pre></td></tr></table></figure>

<p>我们看一下递归和尾递归执行过程：<br>递归：</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">function sum(n) &#123;</span><br><span class="line">    if (n === <span class="number">1</span>) return <span class="number">1</span>;</span><br><span class="line">    return n + sum(n - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line">sum(<span class="number">5</span>)</span><br><span class="line">(<span class="number">5</span> + sum(<span class="number">4</span>))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + sum(<span class="number">3</span>)))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + (<span class="number">3</span> + sum(<span class="number">2</span>))))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + (<span class="number">3</span> + (<span class="number">2</span> + sum(<span class="number">1</span>)))))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + (<span class="number">3</span> + (<span class="number">2</span> + <span class="number">1</span>))))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + (<span class="number">3</span> + <span class="number">3</span>)))</span><br><span class="line">(<span class="number">5</span> + (<span class="number">4</span> + <span class="number">6</span>))</span><br><span class="line">(<span class="number">5</span> + <span class="number">10</span>)</span><br><span class="line"><span class="number">15</span>      <span class="comment">//递归非常消耗内存，因为需要同时保存很多的调用帧，这样，就很容易发生“栈溢出”</span></span><br></pre></td></tr></table></figure>

<p>尾递归：</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function sum(x, total) &#123;</span><br><span class="line">    if (x === <span class="number">1</span>) &#123;</span><br><span class="line">        return x + total;</span><br><span class="line">    &#125;</span><br><span class="line">    return sum(x - <span class="number">1</span>, x + total);</span><br><span class="line">&#125;</span><br><span class="line">sum(<span class="number">5</span>, <span class="number">0</span>)</span><br><span class="line">sum(<span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">sum(<span class="number">3</span>, <span class="number">9</span>)</span><br><span class="line">sum(<span class="number">2</span>, <span class="number">12</span>)</span><br><span class="line">sum(<span class="number">1</span>, <span class="number">14</span>)</span><br><span class="line"><span class="number">15</span></span><br></pre></td></tr></table></figure>

<p>整个计算过程是线性的，调用一次sum(x, total)后，会进入下一个栈，相关的数据信息和跟随进入，不再放在堆栈上保存。当计算完最后的值之后，直接返回到最上层的sum(5,0)。这能有效的防止堆栈溢出。 在ECMAScript 6，我们将迎来尾递归优化，通过尾递归优化，javascript代码在解释成机器码的时候，将会向while看起，也就是说，同时拥有数学表达能力和while的效能。</p>
<h6 id="5-惰性计算（求值）"><a href="#5-惰性计算（求值）" class="headerlink" title="5.惰性计算（求值）"></a>5.惰性计算（求值）</h6><p>在惰性计算中，表达式不是在绑定到变量时立即计算，而是在求值程序需要产生表达式的值时进行计算。延迟的计算使你可以编写可能潜在地生成无穷输出的函数。因为不会计算多于程序的其余部分所需要的值，所以不需要担心由无穷计算所导致的 out-of-memory 错误。简单的来说就是：</p>
<blockquote>
<p><strong>按需索取，能不多做事，绝不多做</strong></p>
</blockquote>
<p>这里有自己实现的简单的惰性求值<br><a href="https://www.ctolib.com/mip/wangdashuaihenshuai-lazy.html" target="_blank" rel="noopener">用JavaScript写一个惰性求值的最简实现</a><br>惰性求值官方文档<br><a href="https://github.com/dtao/lazy.js" target="_blank" rel="noopener">官方文档</a></p>
<h2 id="四、函数式编程总结"><a href="#四、函数式编程总结" class="headerlink" title="四、函数式编程总结"></a>四、函数式编程总结</h2><p>1.函数式编程中的每个符号都是 const 的，于是没有什么函数会有副作用。谁也不能在运行时修改任何东西，也没有函数可以修改在它的作用域之外修改什么值给其他函数继续使用。这意味着决定函数执行结果的唯一因素就是它的返回值，而影响其返回值的唯一因素就是它的参数。<br>2.函数式编程不需要考虑”死锁”（deadlock），因为它不修改变量，所以根本不存在”锁”线程的问题。不必担心一个线程的数据，被另一个线程修改，所以可以很放心地把工作分摊到多个线程，部署”并发编程”（concurrency）。<br>3.函数式编程中所有状态就是传给函数的参数，而参数都是储存在栈上的。这一特性让软件的热部署变得十分简单。只要比较一下正在运行的代码以及新的代码获得一个diff，然后用这个diff更新现有的代码，新代码的热部署就完成了。</p>
<h4 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h4><p><a href="https://llh911001.gitbooks.io/mostly-adequate-guide-chinese/content/" target="_blank" rel="noopener">JavaScript函数式编程指南</a></p>

      
    </div>
    
    
    

    

    

    
    <div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/函数式编程-高级函数-JavaScript/" rel="tag"><i class="fa fa-tag"></i>  函数式编程 高级函数 JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/08/23/前端基础知识点总结JS篇/" rel="next" title="前端基础知识点总结JS篇">
                <i class="fa fa-chevron-left"></i> 前端基础知识点总结JS篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/12/21/JS异步编程及常见面试题/" rel="prev" title="JS异步编程及常见面试题">
                JS异步编程及常见面试题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="http://tva2.sinaimg.cn/crop.0.0.768.768.1024/6cc1c2cfjw8eh3kv8yvs9j20lc0lcdgl.jpg" alt="YauCheun">
            
              <p class="site-author-name" itemprop="name">YauCheun</p>
              <p class="site-description motion-element" itemprop="description">YauCheun</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/YauCheun" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yaucheung@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/YauCheun" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-crosshairs"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#正文"><span class="nav-number">1.</span> <span class="nav-text">正文</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、什么是函数式编程？"><span class="nav-number">1.0.1.</span> <span class="nav-text">一、什么是函数式编程？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、函数式编程的特性"><span class="nav-number">1.0.2.</span> <span class="nav-text">二、函数式编程的特性</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#1-函数是”第一等公民”"><span class="nav-number">1.0.2.0.0.1.</span> <span class="nav-text">1.函数是”第一等公民”</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#2-只用”表达式”，不用”语句”"><span class="nav-number">1.0.2.0.0.2.</span> <span class="nav-text">2.只用”表达式”，不用”语句”</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#3-没有”副作用”"><span class="nav-number">1.0.2.0.0.3.</span> <span class="nav-text">3.没有”副作用”</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#4-不修改状态"><span class="nav-number">1.0.2.0.0.4.</span> <span class="nav-text">4.不修改状态</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#5-引用透明性"><span class="nav-number">1.0.2.0.0.5.</span> <span class="nav-text">5.引用透明性</span></a></li></ol></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#三、函数式编程常用核心概念和技术"><span class="nav-number">1.1.</span> <span class="nav-text">三、函数式编程常用核心概念和技术</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#1-纯函数"><span class="nav-number">1.1.0.0.0.1.</span> <span class="nav-text">1.纯函数</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#2-函数柯里化（高级函数）"><span class="nav-number">1.1.0.0.0.2.</span> <span class="nav-text">2.函数柯里化（高级函数）</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#3-函数组合"><span class="nav-number">1.1.0.0.0.3.</span> <span class="nav-text">3.函数组合</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#4-递归与尾递归"><span class="nav-number">1.1.0.0.0.4.</span> <span class="nav-text">4.递归与尾递归</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#5-惰性计算（求值）"><span class="nav-number">1.1.0.0.0.5.</span> <span class="nav-text">5.惰性计算（求值）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、函数式编程总结"><span class="nav-number">1.2.</span> <span class="nav-text">四、函数式编程总结</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#参考文献"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">参考文献</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-[object Object]"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">YauCheun</span>

  
</div>


   <div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span> 

<i class="fa fa-eye"></i>
<span id="busuanzi_container_site_pv">
    本站总访问量:<span id="busuanzi_value_site_pv"></span>次
</span>
</div>
 









<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共31.4k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

</body>
</html>
